package com.chookss.home.audit.project;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.audit.reimbursement.ReimbursementDetailActivity;
import com.chookss.home.entity.CostEntity;
import com.chookss.home.entity.WorkNewEntity;
import com.chookss.mine.personal.PersonalHomeActivity;
import com.chookss.tools.ClearMoreZeroUtil;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.CircleImageView;
import com.google.gson.reflect.TypeToken;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

public class GroupReimbursementActivity extends BaseAct {
    //项目开支
    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.tvInit)
    TextView tvInit;
    @BindView(R.id.tvData)
    TextView tvData;
    @BindView(R.id.rvView)
    RecyclerView recyclerView;
    @BindView(R.id.srlView)
    SmartRefreshLayout smrRf;
    private ReimbursementAdapter reimbursementAdapter;
    private List<WorkNewEntity> reimbursementList = new ArrayList<>();
    private CostAdapter costAdapter;
    private List<CostEntity> costList = new ArrayList<>();
    private int currentPage = 1;
    private int pageSize = 20;
    private boolean isEnd = false;//是否到底
    private View emptyView;
    private TextView tvNone;//空布局;
    private int type = 0;//  0项目开支列表 1人力成本列表
    private String groupData = "", groupCode = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_reimbursement);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        type = getIntent().getIntExtra("type", 0);
        groupData = getIntent().getStringExtra("groupData");
        groupCode = getIntent().getStringExtra("groupCode");
        tvData.setText(ClearMoreZeroUtil.subZeroAndDot(groupData));
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        emptyView = LayoutInflater.from(this).inflate(R.layout.layout_common_empty, recyclerView, false);
        tvNone = emptyView.findViewById(R.id.tvEmpty);
        tvNone.setText("暂无记录");
        if (0 == type) {
            commonTitleTxt.setText("项目开支");
            tvInit.setText("累计项目开支金额(元)");
            reimbursementAdapter = new ReimbursementAdapter(R.layout.item_reimbursement_record, this, reimbursementList);
            recyclerView.setAdapter(reimbursementAdapter);
        } else {
            commonTitleTxt.setText("人力成本");
            tvInit.setText("累计人力成本(元)");
            costAdapter = new CostAdapter(R.layout.item_group_cost, this, costList);
            recyclerView.setAdapter(costAdapter);
        }

        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    if (type == 0) {
                        getReimbursementListData();
                    } else {
                        getCostListData();
                    }
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                if (type == 0) {
                    getReimbursementListData();
                } else {
                    getCostListData();
                }
            }
        });
        smrRf.autoRefresh();
    }

    private void getReimbursementListData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        map.put("groupCode", groupCode);
        map.put("type", "1,5");
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<WorkNewEntity>>>() {
        }.getType(), null, Urls.selectBaoxiaoEmpList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<WorkNewEntity>>() {
            @Override
            public void onSuccess(List<WorkNewEntity> data) {
                if (currentPage == 1) {
                    reimbursementList.clear();
                    reimbursementAdapter.notifyDataSetChanged();
                }
                if (smrRf == null) {
                    return;
                }
                if (data != null && data.size() > 0) {
                    if (data.size() < pageSize) {
                        isEnd = true;
                    }
                    int old = reimbursementList.size();
                    reimbursementList.addAll(data);
                    reimbursementAdapter.notifyItemRangeChanged(old, data.size());
                    smrRf.setVisibility(View.VISIBLE);
                } else {
                    isEnd = true;
                    if (reimbursementList.size() == 0) {
                        reimbursementAdapter.setEmptyView(emptyView);
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    private void getCostListData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        map.put("groupCode", groupCode);
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<CostEntity>>>() {
        }.getType(), null, Urls.selectItemLaborCostsInfoList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<CostEntity>>() {
            @Override
            public void onSuccess(List<CostEntity> data) {
                if (currentPage == 1) {
                    costList.clear();
                    costAdapter.notifyDataSetChanged();
                }
                if (smrRf == null) {
                    return;
                }
                if (data != null && data.size() > 0) {
                    if (data.size() < pageSize) {
                        isEnd = true;
                    }
                    int old = costList.size();
                    costList.addAll(data);
                    costAdapter.notifyItemRangeChanged(old, data.size());
                    smrRf.setVisibility(View.VISIBLE);
                } else {
                    isEnd = true;
                    if (costList.size() == 0) {
                        costAdapter.setEmptyView(emptyView);
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    class ReimbursementAdapter extends BaseQuickAdapter<WorkNewEntity, BaseViewHolderEx> {
        private Activity context;

        public ReimbursementAdapter(int layoutResId, Activity context, @io.reactivex.annotations.Nullable List<WorkNewEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, WorkNewEntity entity) {
            TextView tvTitle = helper.getView(R.id.tvTitle);
            TextView tvTitleType = helper.getView(R.id.tvTitleType);
            TextView tvMoney = helper.getView(R.id.tvMoney);
            TextView tvTime = helper.getView(R.id.tvTime);
            TextView tvPost = helper.getView(R.id.tvPost);
            TextView tvGroup = helper.getView(R.id.tvGroup);
            TextView tvInit = helper.getView(R.id.tvInit);
            LinearLayout llMoney = helper.getView(R.id.llMoney);
            LinearLayout llGroup = helper.getView(R.id.llGroup);
            LinearLayout llPost = helper.getView(R.id.llPost);
            tvTitle.setText(entity.getCreateEmployeeName() + "的" + entity.getBaoxiaoTypeName() + "申请");
            tvTime.setText("发起时间：" + entity.getCreateTime());
            if("1".equals(entity.getType())){
                tvMoney.setText("报销金额：" + ClearMoreZeroUtil.subZeroAndDot(entity.getAmt()) + "元");
            }else{
                tvMoney.setText("补贴金额：" + ClearMoreZeroUtil.subZeroAndDot(entity.getAmt()) + "元");
            }
            llMoney.setVisibility(View.VISIBLE);
           if (!Utils.isNull(entity.getRemark())) {
                tvInit.setText(entity.getRemark());
            } else {
                tvInit.setText("无");
            }
            if (Utils.isNull(entity.getGroupName())) {
                llGroup.setVisibility(View.GONE);
            } else {
                llGroup.setVisibility(View.VISIBLE);
                tvGroup.setText("所属项目组：" + entity.getGroupName());
            }
            if (Utils.isNull(entity.getOrgName())) {
                llPost.setVisibility(View.GONE);
            } else {
                llPost.setVisibility(View.VISIBLE);
                tvPost.setText("所属部门：" + entity.getOrgName());
            }
            if ("0".equals(entity.getAuditCd())) {
                tvTitleType.setText("审批中");
                tvTitleType.setTextColor(Color.parseColor("#FCA817"));
                tvTitleType.setBackgroundResource(R.drawable.shape_fca817_4_1f);
            } else if ("1".equals(entity.getAuditCd())) {
                tvTitleType.setText("已通过");
                tvTitleType.setTextColor(Color.parseColor("#44D3B3"));
                tvTitleType.setBackgroundResource(R.drawable.shape_44d3b3_4_2f);
            } else {
                if ("3".equals(entity.getAuditCd())) {
                    tvTitleType.setText("废弃");
                } else {
                    tvTitleType.setText("不通过");
                }
                tvTitleType.setTextColor(Color.parseColor("#F2434D"));
                tvTitleType.setBackgroundResource(R.drawable.shape_f2434d_4_2f);
            }
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    Intent intent = new Intent(context, ReimbursementDetailActivity.class);
                    entity.setProjectCode(entity.getBaoxiaoCode());
                    intent.putExtra("data", entity);
                    if("1".equals(entity.getType())){
                        intent.putExtra("type", 7);
                    }else{
                        intent.putExtra("type", 10);
                    }
                    context.startActivity(intent);
                }

            });
        }
    }
    class CostAdapter extends BaseQuickAdapter<CostEntity, BaseViewHolderEx> {
        private Activity context;

        public CostAdapter(int layoutResId, Activity context, @io.reactivex.annotations.Nullable List<CostEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, CostEntity entity) {

            TextView tvName = helper.getView(R.id.tvName);
            TextView tvPost = helper.getView(R.id.tvPost);
            TextView tvNum = helper.getView(R.id.tvNum);
            CircleImageView ivImg = helper.getView(R.id.ivImg);
            View line = helper.getView(R.id.line);
            GlideUtils.loadAvatar(GroupReimbursementActivity.this,entity.getHeadPhotoThumbUrl(),ivImg);
            tvName.setText(entity.getEmployeeName());
            tvPost.setText(entity.getPostName());
            int addSalary = Utils.changeNumber(entity.getBaseSalary()) + Utils.changeNumber(entity.getPostSalary()) + Utils.changeNumber(entity.getWorkSalary());
            tvNum.setText(addSalary+"元");
            if(helper.getItemPosition()==0){
                line.setVisibility(View.GONE);
            }else{
                line.setVisibility(View.VISIBLE);
            }
            ivImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(GroupReimbursementActivity.this, PersonalHomeActivity.class);
                    intent.putExtra("employeeCode",entity.getEmployeeCode());
                    startActivity(intent);
                }
            });
        }
    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    @OnClick(R.id.common_title_back)
    public void onClick() {
        finish();
    }
}
